﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using TharpPhoneBookGUILab.Model;

namespace TharpPhoneBookGUILab.Controller
{
    /// <summary>
    /// A controller of a PhoneBook.
    /// Exposes various operations to a PhoneBook
    /// that can be consumed by a UI.
    /// </summary>
    class PhoneBookController
    {
        #region Fields

        private PhoneBook _Book;

        #endregion

        #region Constructor

        public PhoneBookController(PhoneBook book)
        {
            _Book = book;
        }//end PhoneBookController

        #endregion

        #region Operations

        /// <summary>
        /// Tells the PhoneBook to load data from a file.
        /// </summary>
        /// <param name="fileName">Name of the file to load from.</param>
        /// <returns>Returns null if operation was successful, otherwise an error code.</returns>
        public string Load(string fileName)
        {
            String error;
            if (_Book.LoadDataFromFile(fileName, out error))
                return null;
            return error;
        }//end Load

        /// <summary>
        /// Tells the PhoneBook to save data to a file.
        /// </summary>
        /// <param name="fileName">Name of the file to save to.</param>
        /// <returns>Returns null if operation was successful, otherwise an error code.</returns>
        public string Save(string fileName)
        {
            String error;
            if (_Book.StoreDataInFile(fileName, out error))
                return null;
            return error;
        }//end Save

        /// <summary>
        /// Tells the PhoneBook to add an entry.
        /// Always succeeds.
        /// </summary>
        /// <param name="entry">The PhoneBookEntry to add.</param>
        public void Put(PhoneBookEntry entry)
        {
            _Book.AddOrReplace(entry);
        }//end Put

        /// <summary>
        /// Finds an entry in the PhoneBook given a Name.
        /// </summary>
        /// <param name="name">The Name to look up.</param>
        /// <returns>Returns the entry found, or null if no match was found.</returns>
        public PhoneBookEntry Get(Name name)
        {
            PhoneBookEntry entry;

            if (_Book.TryFindEntry(name, out entry))
                return entry;
            return null;
        }//end Get

        #endregion


    }//end PhoneBookController
}
